//
//  HMSinaRefreshController.swift
//  ZJCSina
//
//  Created by 朱建超 on 16/11/21.
//  Copyright © 2016年 itHeiMa. All rights reserved.
//

import UIKit

/*
 KVO:
 1、添加观察者键值路径
 2、实现观察监听的方法(没有这个方法会崩溃)
 3、移除观察
 */

//下拉状态的枚举
enum RefreshStatue : Int {
    case Normal = 0
    case Already
    case Refresh
}

class HMSinaRefreshController: UIControl {

    //下拉状态的switch
    var statue : RefreshStatue = .Normal{
    
        didSet{
        
            switch statue {
            case .Normal:
                print("--普通状态")
                xiaLaLabel.text = "下拉刷新"
                
                indicator.stopAnimating()
                xiaLaImage.isHidden = false
                
                UIView.animate(withDuration: 0.25, animations: {
                    
                    self.xiaLaImage.transform = CGAffineTransform.identity
                    
                })
                //还原，必须是refresh状态-->normal状态的时候减
                if oldValue == .Refresh {
                    UIView.animate(withDuration: 0.5, animations: {
                        
                        self.scrollView?.contentInset.top = (self.scrollView?.contentInset.top)! - 60
                    })
                }
            case .Already:
                print("--准备状态")
                xiaLaLabel.text = "松手刷新"
                //修改箭头的方向
                UIView.animate(withDuration: 0.25, animations: {
                    
                    self.xiaLaImage.transform = CGAffineTransform.init(rotationAngle: CGFloat(M_PI))
                    
                })
            case .Refresh:
                print("--正在刷新状态")
                xiaLaLabel.text = "正在刷新...... "
                indicator.startAnimating()
                xiaLaImage.isHidden = true
                //数据请求结束之后，恢复默认状态
                //如何触发事件
                sendActions(for: .valueChanged)
                //正在刷新状态有悬停的效果(在准备状态时要减去)
                UIView.animate(withDuration: 0.5, animations: {
    
                    self.scrollView?.contentInset.top = (self.scrollView?.contentInset.top)! + 60
                })
                
            }
            
        }
    
    }
    
    //给外界定义结束刷新的方法
    func endRefreshing() {
        
        //swift中延迟执行
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            
            //将statue修改为normal,这个时候延迟一下
            self.statue = .Normal
            
        }
        
    }
    
    //设置一个固定大小
    override init(frame: CGRect) {
        
        let rect = CGRect(x: 0, y: -60, width: UIScreen.main.bounds.width, height: 60)
        
        super.init(frame: rect)
        
        self.backgroundColor = UIColor.white
        
        setupUI()
    
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var scrollView : UIScrollView?
    
    //在什么时候设置KVO观察 -->当刷新控件被添加到父视图上的时候开始设置
    override func willMove(toSuperview newSuperview: UIView?) {
        
        super.willMove(toSuperview: newSuperview)
        
        if let fatherview = newSuperview as? UIScrollView{
            
            self.scrollView = fatherview
            
            //设置观察
            self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil)
        }
        
    }
    
    //观察监听的方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        //拖拉的Y
        let offsetY = self.scrollView?.contentOffset.y ?? 0
        
        //目标位置的y
        let targetOffectY = -(self.scrollView!.contentInset.top + 60)
        
        //下拉时候的状态判断
        if scrollView!.isDragging {
            
            //正在被拽动
            //offsetY 和 targetOffectY进行比较，判断
            if offsetY < targetOffectY && statue == .Normal{
                //准备刷新状态
                statue = .Already
            }else if offsetY > targetOffectY && statue == .Already{
                //默认状态
                statue = .Normal
            }
            
        }else{
        
            //用户停止拽动tableView && 当前状态是准备刷新状态 -->正在刷新状态
            if statue == .Already {
                
                statue = .Refresh
                
            }
            
        }
        
    }
    
    //设置UI界面
    private func setupUI() {
        
        addSubview(xiaLaLabel)
        addSubview(xiaLaImage)
        addSubview(indicator)
        addSubview(backImageView)
        
        xiaLaLabel.snp.makeConstraints { (make) in
            
            make.centerX.equalTo(self.snp.centerX).offset(10)
            make.centerY.equalTo(self.snp.centerY)
            
        }
        
        xiaLaImage.snp.makeConstraints { (make) in
            
            make.right.equalTo(xiaLaLabel.snp.left).offset(-5)
            make.centerY.equalTo(xiaLaLabel.snp.centerY)
            
        }
        
        indicator.snp.makeConstraints { (make) in
            
            make.center.equalTo(xiaLaImage.snp.center)
            
        }
        
        backImageView.snp.makeConstraints { (make) in
        
            make.left.right.bottom.equalTo(self) 
            
        }
        
    }
    
    //懒加载控件
    private lazy var xiaLaLabel : UILabel = UILabel(title: "下拉起飞", font: 16, textColor: UIColor.orange)
    private lazy var xiaLaImage : UIImageView = UIImageView(image: #imageLiteral(resourceName: "tableview_pull_refresh"))
    private lazy var indicator : UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
    
    private lazy var backImageView : UIImageView = UIImageView(image: #imageLiteral(resourceName: "refreshbg"))
    
    //移除观察者
    deinit {
        
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
        
    }

}
